package com.lzy.cloud.payment.service.impl;

import com.lzy.cloud.payment.service.SerialNumberService;
import com.lzy.framework.core.cache.cluster.RedisClusterService;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.lock.RedisGlobalLock;
import com.lzy.framework.tools.date.DateStyle;
import com.lzy.framework.tools.date.DateUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 
 * Description:支付交易流水号
 * 
 * @author lc Create Date Time:Mar 23, 2017 2:14:29 PM
 */
@Service
public class SerialNumberServiceImpl implements SerialNumberService {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(SerialNumberServiceImpl.class);
	@Autowired
	private RedisGlobalLock redisGlobalLock;
	@Autowired
	private RedisClusterService redisClusterService;

	
	@Override
	public Long createSerialNumber(String biz,String type,Long userId) {
		try {
			if (StringUtils.isBlank(biz))
				return null;
			if (redisGlobalLock.lock(biz)){
				String date = DateUtils.DateToString(null,
						DateStyle.MMDD);
				String key = type + biz + date;// key
				String start = biz + date;
				String v = redisClusterService.get(key, String.class);
				String s = null;// value
				if (null == v) {// 每天第一次生成
					s = start + "100" + RandomStringUtils.random(6, false, true);
					redisClusterService.set(key, s, Integer.MAX_VALUE);
				} else {
					v = v.substring( v.length() - 7, v.length());
					Integer returnInt = Integer.valueOf(v);
					returnInt++;
					v = start + returnInt;
					redisClusterService.set(key, v, Integer.MAX_VALUE);
					s = v;
				}
				redisGlobalLock.unlock(biz);
				return Long.valueOf(s);
			}
		} catch (Exception e) {
			LOGGER.info("获取订单编号失败", e);
			Ensure.that(e).isNotNull("09000001");
		}
		return null;
	}
}
